package com.zzl.admin.service.admin.impl;

import com.zzl.admin.common.Constats;
import com.zzl.admin.dao.base.BaseDao;
import com.zzl.admin.dao.admin.ResourceDao;
import com.zzl.admin.entity.admin.Resource;
import com.zzl.admin.entity.admin.Role;
import com.zzl.admin.service.admin.ResourceService;
import com.zzl.admin.service.admin.RoleService;
import com.zzl.admin.service.base.impl.BaseServiceImpl;
import com.zzl.admin.utils.EmptyUtil;
import com.zzl.admin.vo.ZtreeView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Description：资源服务接口实现类
 * Created by 朱正磊 on 2019-03-22 17:42
 */
@Service
public class ResourceServiceImpl extends BaseServiceImpl<Resource, Integer> implements ResourceService {

    private final ResourceDao resourceDao;

    private final RoleService roleService;

    @Autowired
    public ResourceServiceImpl(ResourceDao resourceDao, @Lazy RoleService roleService) {
        this.resourceDao = resourceDao;
        this.roleService = roleService;
    }

    @Override
    public BaseDao<Resource, Integer> getBaseDao() {
        return resourceDao;
    }

    /**
     * description：获取角色的权限树（添加缓存）
     * user 朱正磊
     * time 2019-03-23 14:53
     * @param roleId 角色ID
     * @return 返回权限树列表
     */
    @Override
    @Cacheable(value = Constats.RESOURCE_CACHE_NAME, key = "'tree_' + #roleId")
    public List<ZtreeView> tree(int roleId) {
        //创建权限树节点列表
        List<ZtreeView> treeNodes = new ArrayList<>();
        //根据角色ID查询指定角色
        Role role = roleService.findById(roleId);
        //查询指定角色拥有的资源
        Set<Resource> roleResources = role.getResources();
        //添加最顶层权限树节点---系统菜单（无父节点）
        treeNodes.add(new ZtreeView(0L, null, "系统菜单", true));
        //查询所有的资源
        List<Resource> allResource = resourceDao.findAllByOrderByParentAscIdAscSortAsc();
        //定义权限树节点
        ZtreeView treeNode;
        //往权限树节点列表里面添加权限树节点
        for (Resource resource : allResource) {
            treeNode = new ZtreeView();
            //设置权限树节点的ID
            treeNode.setId(Long.valueOf(resource.getId()));
            //设置权限树节点的父节点ID
            if (EmptyUtil.isEmpty(resource.getParent())) {
                treeNode.setPId(0L);
            } else {
                treeNode.setPId(Long.valueOf(resource.getParent().getId()));
            }
            //设置权限树节点的名称
            treeNode.setName(resource.getName());
            //判断角色是否拥有该权限树节点
            if (EmptyUtil.isNotEmpty(roleResources) && roleResources.contains(resource)) {
                treeNode.setChecked(true);
            }
            treeNodes.add(treeNode);
        }
        return treeNodes;
    }

    /**
     * description：修改或者新增资源
     * user 朱正磊
     * time 2019-03-23 14:53
     * @param resource 资源对象
     */
    @Override
    public void saveOrUpdate(Resource resource) {
        if (EmptyUtil.isNotEmpty(resource.getId())) { //主键不为空表示修改
            Resource dbResource = findById(resource.getId()); //根据主键查找唯一数据

            //设置属性值
            dbResource.setName(resource.getName()); //资源名称
            dbResource.setSourceKey(resource.getSourceKey()); //资源唯一标识
            dbResource.setType(resource.getType()); //资源类型
            dbResource.setSourceUrl(resource.getSourceUrl()); //资源url
            dbResource.setLevel(resource.getLevel()); //层级
            dbResource.setSort(resource.getSort()); //排序
            dbResource.setIsHide(resource.getIsHide()); //是否隐藏
            dbResource.setIcon(resource.getIcon()); //图标
            dbResource.setDescription(resource.getDescription()); //描述
            dbResource.setUpdateTime(new Date()); //更新时间
            dbResource.setParent(resource.getParent()); //父资源

            update(dbResource); //更新资源
        } else { //主键为空表示新增
            resource.setCreateTime(new Date()); //创建时间
            resource.setUpdateTime(new Date()); //更新时间
            save(resource); //保存资源
        }
    }

    /**
     * description：根据查询条件获取分页
     * user 朱正磊
     * time 2019-03-23 14:54
     * @param searchText 查询条件
     * @param pageRequest 分页请求对象
     * @return 返回分页对象
     */
    @Override
    public Page<Resource> findAllByLike(String searchText, PageRequest pageRequest) {
        if (EmptyUtil.isEmpty(searchText)) {
            searchText = "";
        }
        return resourceDao.findAllByNameContaining(searchText, pageRequest);
    }

    /**
     * description：删除一条记录（重写）
     * user 朱正磊
     * time 2019-03-25 09:34
     * @param id 主键
     */
    @Override
    public void delete(Integer id) {
        //根据资源ID删除角色资源关联表里的数据
        resourceDao.deleteGrand(id);
        //调用父类的删除方法删除该数据
        super.delete(id);
    }

}
